<?
header("Content-Type: text/html; charset=utf-8");

/* Database connection function */
function connectDB()
{
    mysql_connect("localhost","root","");
    mysql_selectdb("rare");    
} /* End of Database connection function */


/* getElementById Function */


function getElementById( $table, $id )
{
    $query = mysql_query("SELECT * FROM ".$table." WHERE id = '".$id."' LIMIT 1");
     if($query)
      {  
        $fetchResult = mysql_fetch_array($query);
         return $fetchResult;
      } else 
    return "Error: query has no result";
    
} /* End of getElementById function */ 

function putToDB($table, $cols, $values)
{
    mysql_query("INSERT INTO ".$table." (".$cols.") VALUES (".$values.") ");
}

/* getElementsById function */
function getElementsById( $table, $id)
{
    $query = mysql_query("SELECT * FROM ".$table." WHERE id = ".$id);
     if($query)
    while($fetchResult = mysql_fetch_array($query))
     $elementsArray[] = $fetchResult;
    return $elementsArray;
} 


/* Get UsersByTag function Returns array(id, name, body, time, score) */
function getUsersByTag( $tag )
{
    $queryGetTagID = mysql_query("SELECT * FROM tags WHERE tag='".$tag."'");
     $arrayTagID = mysql_fetch_array($queryGetTagID);
      
        $queryGetUsersIDs = mysql_query("SELECT * FROM tagnuser WHERE tag = ".$arrayTagID['id']);
         $arrayUsersIDs = mysql_fetch_array($queryGetUsersIDs);
        
        foreach($arrayUsersIDs as $key => $userID)
        {            
             $arrayOfUsers[] = getElementById("users", $userID);
        } 
      return $arrayOfUsers;                
} /* End of GetUsersByTag function */

function getCategories($limit)
{
    $query = mysql_query("SELECT * FROM categories ORDER BY score DESC LIMIT ".$limit);
    while($result = mysql_fetch_array($query))
     $results[] = $result;     
    return $results;      
    
}

/* Search function. Returns array. */
function search( $table, $cols, $query, $mode)
{
    if($mode == "FULLTEXT")
     $query = mysql_query("SELECT * FROM ".$table." WHERE MATCH  (".$cols.")  AGAINST ('".addslashes($query)."')");
    elseif($mode == "LIKE")
     $query = mysql_query("SELECT * FROM ".$table." WHERE (".$cols.") LIKE ('%".addslashes($query)."%')"); 
     
    while($result = mysql_fetch_array($query))
     $arraySearchResults[] = $result;
    return $arraySearchResults;  
} /* End of search function */

function postQuery( $query, $body = '' )
{
    if($body && $query)    
     putToDB("queries", "query, body", "'".$query."','".$body."'");
    elseif( $body )
       putToDB("queries", "query", "'".$query."'");     
}

?>